#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
HAI优化系统简单测试脚本
"""

import sys
import time
import logging
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def test_config():
    """测试配置"""
    logger.info("测试配置...")
    
    try:
        from config.config import validate_config, CONFIG
        
        errors = validate_config()
        if errors:
            logger.warning(f"配置验证警告: {errors}")
        else:
            logger.info("配置验证通过")
        
        logger.info(f"配置节数量: {len(CONFIG)}")
        return True
        
    except Exception as e:
        logger.error(f"配置测试失败: {e}")
        return False


def test_user_identification():
    """测试用户识别"""
    logger.info("测试用户识别...")
    
    try:
        from core.user_identification import user_identifier
        
        # 测试用户识别
        test_ip = "192.168.1.100"
        user_id1 = user_identifier.identify_user(test_ip)
        logger.info(f"用户ID 1: {user_id1}")
        
        # 测试统计信息
        stats = user_identifier.get_user_statistics()
        logger.info(f"用户统计: {stats}")
        
        return True
        
    except Exception as e:
        logger.error(f"用户识别测试失败: {e}")
        return False


def test_fair_queue():
    """测试公平队列"""
    logger.info("测试公平队列...")
    
    try:
        from core.user_identification import fair_queue
        
        # 添加测试任务
        fair_queue.add_task("task_001", "192.168.1.100", {"image": "test1.jpg"})
        fair_queue.add_task("task_002", "192.168.1.101", {"image": "test2.jpg"})
        
        # 获取队列状态
        status = fair_queue.get_queue_status()
        logger.info(f"队列状态: {status}")
        
        # 获取下一个任务
        task = fair_queue.get_next_task()
        if task:
            logger.info(f"下一个任务: {task['task_id']} -> {task['user_id']}")
        
        return True
        
    except Exception as e:
        logger.error(f"公平队列测试失败: {e}")
        return False


def test_logging_system():
    """测试日志系统"""
    logger.info("测试日志系统...")
    
    try:
        from core.logging_system import structured_logger
        
        # 测试任务处理日志
        structured_logger.log_task_processing(
            task_id="test_task_001",
            user_id="user_192.168.1.100_1",
            client_ip="192.168.1.100",
            time_window=1,
            server_id="gpu-001",
            region="ap-beijing",
            gpu_type="basic",
            submit_time=time.time() - 30,
            start_time=time.time() - 25,
            complete_time=time.time(),
            status="success",
            processing_duration=25,
            wait_duration=5
        )
        
        logger.info("日志记录测试完成")
        return True
        
    except Exception as e:
        logger.error(f"日志系统测试失败: {e}")
        return False


def test_task_distribution():
    """测试任务分配"""
    logger.info("测试任务分配...")
    
    try:
        from core.task_distribution import LoadBalancer, Server
        
        # 创建负载均衡器
        lb = LoadBalancer()
        
        # 添加测试服务器
        server1 = Server("server-001", "ap-beijing", "basic", endpoint="http://server1.example.com")
        server2 = Server("server-002", "ap-nanjing", "standard", endpoint="http://server2.example.com")
        
        lb.add_server(server1)
        lb.add_server(server2)
        
        # 获取系统指标
        metrics = lb.get_system_metrics()
        logger.info(f"系统指标: {metrics}")
        
        return True
        
    except Exception as e:
        logger.error(f"任务分配测试失败: {e}")
        return False


def main():
    """主测试函数"""
    logger.info("开始HAI优化系统简单测试...")
    
    tests = [
        ("配置", test_config),
        ("用户识别", test_user_identification),
        ("公平队列", test_fair_queue),
        ("日志系统", test_logging_system),
        ("任务分配", test_task_distribution),
    ]
    
    passed = 0
    failed = 0
    
    for test_name, test_func in tests:
        try:
            logger.info(f"\n{'='*50}")
            logger.info(f"运行测试: {test_name}")
            logger.info(f"{'='*50}")
            
            if test_func():
                logger.info(f"✅ {test_name} 测试通过")
                passed += 1
            else:
                logger.error(f"❌ {test_name} 测试失败")
                failed += 1
                
        except Exception as e:
            logger.error(f"❌ {test_name} 测试异常: {e}")
            failed += 1
    
    logger.info(f"\n{'='*50}")
    logger.info(f"测试结果: 通过 {passed}, 失败 {failed}")
    logger.info(f"{'='*50}")
    
    if failed == 0:
        logger.info("🎉 所有测试通过！")
        return True
    else:
        logger.error(f"💥 {failed} 个测试失败")
        return False


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
